package com.boot.core.util

import com.alibaba.fastjson.JSON
import com.boot.config.ParamConfig
import com.boot.mgt.dao.mysql.TaAddressMapper
import com.boot.mgt.dao.mysql.TaDistrictMapper
import com.boot.mgt.dao.mysql.TaStreetMapper
import com.boot.mgt.model.TaAddress
import com.boot.mgt.model.TaDistrict
import com.boot.mgt.model.TaStreet
import okhttp3.OkHttpClient
import okhttp3.Request
import org.apache.commons.lang3.StringUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.util.*

/**
 * @author kawins
 * createTime 2019-03-26 21:27
 */
@Component
class PositionApi {

    @Autowired
    private lateinit var streetMapper: TaStreetMapper

    @Autowired
    private lateinit var addressMapper: TaAddressMapper

    @Autowired
    protected lateinit var districtMapper: TaDistrictMapper

    @Autowired
    private lateinit var paramConfig: ParamConfig

    @Throws(Exception::class)
    fun send(amapLongitude: Double?, amapLatitude: Double?): ApiBean? {
        if (amapLongitude == null && amapLatitude == null) {
            return null
        }
        val request = Request.Builder()
                .url("${paramConfig.geocoding.reverseGeocodingApiURL}/$amapLongitude,$amapLatitude")
                .get().build()
        val response = OK_HTTP_CLIENT.newCall(request).execute()
        if (response.isSuccessful) {
            response.body()?.let {
                it.string()?.let {
                    log.info("获取位置信息成功")
                    val json = JSON.parseObject(it)
                    val locationList = json["location_list"].toString()
                    ApiBean().apply {
                        this.geojsonList = json["geojson_list"].toString()
                        this.locationIdList = json["location_id_list"].toString()
                        this.amapDistrict = json["district"].toString()
                        val parseArray = JSON.parseArray(locationList)
                        this.amapStreet = parseArray[0].toString()
                        this.amapAddress = "${parseArray[0]}${parseArray[1]}"
                        savePosition(this)
                        return this
                    }
                }
            }
        } else {
            log.warn("获取位置信息接口请求失败,返回码:[{}]", response.code())
        }
        return null
    }

    fun savePosition(apiBean: ApiBean) {
        if (StringUtils.isNotBlank(apiBean.amapDistrict) &&
                StringUtils.isNotBlank(apiBean.amapStreet) &&
                StringUtils.isNotBlank(apiBean.amapAddress)) {
            val taDistrict = TaDistrict()
            taDistrict.name = apiBean.amapDistrict
            val district = districtMapper.selectOne(taDistrict)
            if (district == null) {
                taDistrict.addTime = Date()
                districtMapper.insertSelective(taDistrict)
                apiBean.districtId = taDistrict.id
            } else {
                apiBean.districtId = district.id
            }
            val taStreet = TaStreet()
            taStreet.name = apiBean.amapStreet ?: ""
            taStreet.districtId = apiBean.districtId
            val street = streetMapper.selectOne(taStreet)
            if (street == null) {
                taStreet.addTime = Date()
                taStreet.districtId = apiBean.districtId
                streetMapper.insertSelective(taStreet)
                apiBean.streetId = taStreet.id
            } else {
                apiBean.streetId = street.id
            }
            val taAddress = TaAddress()
            taAddress.streetId = apiBean.streetId
            taAddress.name = apiBean.amapAddress ?: ""
            val address = addressMapper.selectOne(taAddress)
            if (address == null) {
                taAddress.addTime = Date()
                taAddress.streetId = apiBean.streetId
                addressMapper.insertSelective(taAddress)
                apiBean.addressId = taAddress.id
            } else {
                apiBean.addressId = address.id
            }
        } else {
            log.warn("案件ID:{},数据不全无法保存位置信息")
        }
    }

    class ApiBean {
        var locationIdList: String? = null
        var geojsonList: String? = null
        var amapDistrict: String? = null
        var amapStreet: String? = null
        var amapAddress: String? = null
        var districtId: Int? = null
        var streetId: Int? = null
        var addressId: Int? = null

    }


    companion object {

        val OK_HTTP_CLIENT = OkHttpClient()

        private val log: Logger = LoggerFactory.getLogger(this::class.java)

    }

}